#asyncioasyncio is the standard library of Python,
# used for writing single-threaded concurrent code and implementing asynchronous I/O operations
# based on coroutines and event loops.
# It is particularly suitable for handling I/ O-intensive tasks
# such as high-concurrency network requests and file reading and writing.
import asyncio
import os
import pytest
from browser_use import Agent,Controller
from dotenv import load_dotenv
from langchain_openai import  ChatOpenAI
from pydantic import SecretStr
from utils.results_history import Results
from utils.Posts import Posts

# Load the environment variables in the.env file
load_dotenv(dotenv_path="api.env")
#This decorator enables the fixture to work in an asynchronous environment
@pytest.fixture(scope="function")
@pytest.mark.asyncio
#request is a special built-in object
# that provides access to the current test context.
# With the request object, you can get or modify the following information:
# Test function metadata such as test name, parameters, mark, etc.
# Scope and lifetime of the fixture
# Passing parameters to the fixture (via parametrize decorator)
# Access other fixture registration finalizers
async def setUp(request):

   api_key = os.environ.get("OPENAI_API_KEY")

   llm =ChatOpenAI(model = "gpt-4o",api_key=SecretStr(api_key))
   results = Results()
   controller = Controller(output_model=Posts)
   task = ('Open Chrome browser along with website url "https://thehackernews.com/"'
         'Wait for the next steps prompt')

   # asynchronous initialization
   agent = Agent(llm=llm,task=task,controller=controller,use_version=True)
   yield  agent,controller,results
   #asychronous code close
   results.result_history()
   await agent.close()
